package com.cuckoo.cuckoo_app2.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.annotation.Nullable;

import com.cuckoo.cuckoo_app2.MyApplication;
import com.cuckoo.cuckoo_app2.R;
import com.cuckoo.cuckoo_app2.adapters.PlatformToListAdpter;
import com.cuckoo.cuckoo_app2.apiAsync.BaseCallbac;
import com.cuckoo.cuckoo_app2.apiAsync.Imp.PlatformApiImp;
import com.cuckoo.cuckoo_app2.apiAsync.PlatformApi;
import com.cuckoo.cuckoo_app2.business.Imp.PlatListBusinessImp;
import com.cuckoo.cuckoo_app2.business.Imp.PlatformBusinessImp;
import com.cuckoo.cuckoo_app2.business.Imp.SiteLinkBusinessImp;
import com.cuckoo.cuckoo_app2.business.Imp.TipsMessagBusinessImp;
import com.cuckoo.cuckoo_app2.business.PlatListBusiness;
import com.cuckoo.cuckoo_app2.business.PlatformBusiness;
import com.cuckoo.cuckoo_app2.business.SiteLinkBusiness;
import com.cuckoo.cuckoo_app2.business.TipsMessagBusiness;
import com.cuckoo.cuckoo_app2.dao.PlatList;
import com.cuckoo.cuckoo_app2.dao.Platform;
import com.cuckoo.cuckoo_app2.dao.SiteLink;
import com.cuckoo.cuckoo_app2.dao.SysUser;
import com.cuckoo.cuckoo_app2.dao.User;
import com.cuckoo.cuckoo_app2.dao.UserPlatformDao;
import com.cuckoo.cuckoo_app2.utils.DialogUtils;
import com.cuckoo.cuckoo_app2.utils.RouteUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;

import java.util.ArrayList;
import java.util.List;

public class PlatformActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private PlatformToListAdpter adapter;
    private List<PlatList> dataList = new ArrayList<>();
    private TextView pla_m_total, pla_total;
    private Long mTotal, total;
    private Button btn_no_find;
    private Context context;
    private PlatformApi platformApi;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i("TEST", "PlatformActivity.onCreate()");
        context = this;
        setContentView(R.layout.activity_platform);
        platformApi = new PlatformApiImp();

        // 获取统计
        pla_m_total = findViewById(R.id.pla_m_total);
        pla_total = findViewById(R.id.pla_total);
        btn_no_find = findViewById(R.id.btn_no_find);

        // 获取数据
        getData();

        // 选择适配器
        recyclerView = findViewById(R.id.recycler_list);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        // 初始化适配器并设置给 RecyclerView
        adapter = new PlatformToListAdpter(this, dataList, new ButtonClickListener());
        recyclerView.setAdapter(adapter);

        onCountNumber();

        // 跳转添加平台
        btn_no_find.setOnClickListener(view -> {
            RouteUtils.toAddPlatformActivity(this);
        });
    }


    @Override
    protected void onStart() {
        super.onStart();
        Log.i("TEST", "PlatformActivity.onStart()");
        // 检查用户是否已登录
        if (MyApplication.getInstances().getUser() == null) {
            RouteUtils.toLoginActivity(this);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.i("TEST", "PlatformActivity.onStop()");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i("TEST", "PlatformActivity.onDestroy()");
    }

    public void getData() {
        PlatListBusiness platListBusiness = new PlatListBusinessImp();
        dataList = platListBusiness.getPlatList();

        PlatformBusiness platform = new PlatformBusinessImp();
        mTotal = platform.count();

        SiteLinkBusiness siteLink = new SiteLinkBusinessImp();
        total = siteLink.count();
    }

    public void onCountNumber() {
        pla_m_total.setText(mTotal.toString());
        pla_total.setText(total.toString());
    }

    public void clearRecyclerViewData() {
        if (adapter != null) {
            adapter.clearData(); // 调用适配器的方法来清空数据
        }
    }

    public void updateRecyclerViewData() {
        if (adapter != null) {
            adapter.updateData(dataList); // 调用适配器的方法来更新数据
        }
    }

    /**
     * 回调按钮
     */
    public class ButtonClickListener {

        /**
         * 移除
         *
         * @param plat
         */
        public void onRemove(PlatList plat) {
            PlatformBusiness platform = new PlatformBusinessImp();
            platform.delete(plat.getId());

            TipsMessagBusiness tipsMessagBusiness = new TipsMessagBusinessImp();
            tipsMessagBusiness.delete(plat.getId());
            // 获取数据
            getData();
            onCountNumber();

            updateRecyclerViewData();

            // 同步云
            platformApi.PlatformDeleteAsync(plat.getId(), new BaseCallbac<JsonObject>() {
                @Override
                public void onSuccess(JsonObject data) {
                    Log.i("TEST", "平台同步云成功");
                    runOnUiThread(()->{
                        if (!data.get("success").getAsBoolean()) {
                            DialogUtils.showToast(context, data.get("message").getAsString());
                            return;
                        }
                        DialogUtils.showToast(context, "移除成功");
                    });
                }

                @Override
                public void onFailure(String errorMessage) {
                    Log.e("TEST", "平台同步云失败");
                }
            });
        }

        /**
         * 添加
         *
         * @param plat
         */
        public void onAdd(PlatList plat) {
            // 检测当前是否可用
            User user = MyApplication.getInstances().getUser();
            if (user == null || user.getIsVip() == 0) {
                DialogUtils.showToast(context, "非会员不能操作");
                return;
            }

            SiteLinkBusiness siteLink = new SiteLinkBusinessImp();
            SiteLink sit = siteLink.getByID(plat.getId());

            Platform platform = new Platform();
            platform.setId(sit.getId());
            platform.setImageUrl(sit.getImageUrl());
            platform.setTitle(sit.getTitle());
            platform.setStart(0);
            platform.setIsLogin(0);
            platform.setHasTips(0);
            platform.setRetryCount(0);
            platform.setMessag("未登录");

            PlatformBusiness platformBusiness = new PlatformBusinessImp();
            platformBusiness.insert(platform);

            // 获取数据
            getData();
            onCountNumber();
            updateRecyclerViewData();

            // 添加到云端
            UserPlatformDao userPlatformDao = new UserPlatformDao();
            userPlatformDao.setPlatformId(platform.getId());
            userPlatformDao.setImageUrl(platform.getImageUrl());
            userPlatformDao.setTitle(platform.getTitle());
            userPlatformDao.setStart(platform.getStart());
            userPlatformDao.setIsLogin(platform.getIsLogin());
            userPlatformDao.setHasTips(platform.getHasTips().toString());
            userPlatformDao.setMessag(platform.getMessag());

            // 上传云
            platformApi.PlatformAddAsync(userPlatformDao, new BaseCallbac<JsonObject>() {
                @Override
                public void onSuccess(JsonObject data) {
                    Log.i("TEST", "平台同步云成功");
                    runOnUiThread(()->{
                        if (!data.get("success").getAsBoolean()) {
                            DialogUtils.showToast(context, data.get("message").getAsString());
                            return;
                        }
                        DialogUtils.showToast(context, "添加成功");
                    });
                }

                @Override
                public void onFailure(String errorMessage) {
                    Log.e("TEST", "平台同步云失败");
                }
            });
        }
    }

}
